package com.flyzing.genl.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author yaoguangyao
 * @Date 2020年12月30日
 */
public class DBConnFactory {
	private static String url;
	private static String username;
	private static String password;
	
	private static final DBConnFactory INSTANCE = new DBConnFactory();
	
	private DBConnFactory() {}
	
	public static DBConnFactory getInstance(String driverName, String url, String username, String password) {
		try {
			Class.forName(driverName);
			DBConnFactory.url = url;
			DBConnFactory.username = username;
			DBConnFactory.password = password;
			return INSTANCE;
		} catch (ClassNotFoundException e) {
			throw new RuntimeException("加载数据库驱动失败，driverName: " + driverName);
		}
	}

	public Connection create() {
		Connection conn = null;
		try {
			conn = DriverManager.getConnection(url, username, password);
		} catch (Exception e) {
			throw new RuntimeException("获取数据库连接失败, url: " + url + ", username: " + username + ", password: " + password, e);
		}

		return conn;
	}
	
	public void close(Connection conn, PreparedStatement ps) {
		close(conn, ps, null);
	}
	
	public void close(Connection conn, PreparedStatement ps, ResultSet rs) {
		try {
			if(rs != null) {
				rs.close();
			}
		} catch (SQLException e) {
			throw new RuntimeException("ResultSet关闭失败, rs:" + rs);
		}
		
		try {
			if(ps != null) {
				ps.close();
			}
		} catch (SQLException e) {
			throw new RuntimeException("PreparedStatement关闭失败, ps:" + ps);
		}
		
		try {
			if(conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			throw new RuntimeException("Connection关闭失败, conn:" + conn);
		}
	}
}
